import User from '@/api/system/user'
import {getToken, setToken, removeToken} from '@/api/auth'

const user = {
  state: {
    token: getToken(),
    user: {
      info: null,
      menus: [],
      roles: [],
    }
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user.info = user
    },
    SET_MENUS: (state, menus) => {
      state.user.menus = menus
    },
    SET_ROLES: (state, roles) => {
      state.user.roles = roles
    }
  },

  actions: {
    // 登录
    LoginByUser({commit}, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password.trim()
      const captcha = userInfo.captcha.trim()
      return new Promise((resolve, reject) => {
        User.login(username, password, captcha).then(response => {
          const data = response.data
          let token = response.headers['x-token'] || data.token;
          if (!!token) {
            setToken(token)
            commit('SET_TOKEN', token)
          }
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUser({commit}) {
      return new Promise((resolve, reject) => {
        User.getUser().then(response => {
          const data = response.data
          commit('SET_USER', data.obj)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetMenus({commit}) {
      return new Promise((resolve, reject) => {
        User.getMenus().then(response => {
          var menus = JSON.parse(response.data.obj);
          commit('SET_MENUS', menus)
          resolve(menus)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({commit, state}) {
      return new Promise((resolve, reject) => {
        User.logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
